import React, {Component} from 'react';
import './index.css';
import {produce} from 'immer';
import {random} from 'lodash';
import Header from '@/Todo/components/Header.js';
import Main from '@/Todo/components/Main.js';
import Footer from '@/Todo/components/Footer';
import {ACTIVE, ALL, COMPLETE} from './constants/index';

class App extends Component {
  state = {
    checkAll: false,
    status: ALL,
    list: [
      {
        id: 1,
        title: '学习vue',
        isDone: false,
      },
      {
        id: 2,
        title: '学习react',
        isDone: true,
      },
    ],
  };

  setStatus = (status) => () => {
    this.setState({
      status,
    });
  };

  clear = () => {
    this.setState({
      list: this.state.list.filter((item) => !item.isDone),
    });
  };

  onChange = (id, status) => {
    this.setState(produce((state) => {
      const currentEvent = state.list.find((item) => item.id === id);
      currentEvent.isDone = status;
    }));
  };

  addTodo = (title) => {
    this.setState(produce((state) => {
      //
      state.list.push({
        id: random(100, 1000),
        title,
        isDone: false,
      });
    }));
  };

  delTodo = (id) => () => {
    this.setState({
      list: this.state.list.filter((item) => item.id !== id),
    });
  };

  changeAll = (checked) => {
    this.setState(produce((state) => {
      state.list.forEach((item) => {
        item.isDone = checked;
      });
      state.checkAll = checked;
    }));
  };

  render() {
    const {status} = this.state;
    const showList = this.state.list.filter((item) => {
      if (status === ACTIVE) {
        return !item.isDone;
      }
      if (status === COMPLETE) {
        return item.isDone;
      }
      return true;
    });
    return (
      <section className="todoapp">
        <Header
          addTodo={this.addTodo}
        />
        <Main
          changeAll={this.changeAll}
          checkAll={this.state.checkAll}
          delTodo={this.delTodo}
          status={this.state.status}
          list={showList}
          onChange={this.onChange}
        />
        <Footer
          len={showList.length}
          clear={this.clear}
          status={this.state.status}
          setStatus={this.setStatus}
        />
      </section>
    );
  }
}

export default App;
